package com.dream.keigezhushou.Activity.kege.acty;

import android.media.MediaRecorder;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.dream.keigezhushou.R;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 清唱
 */
public class CantataActivity extends AppCompatActivity {


    @BindView(R.id.cantata_countdown)
    TextView countdownTv;

    @BindView(R.id.cantata_back)
    ImageView backImg;

    @BindView(R.id.cantata_back_1)
    ImageView back1Img;

    @BindView(R.id.cantata_back_2)
    ImageView back2Img;

    @BindView(R.id.cantata_back_3)
    ImageView back3Img;

    @BindView(R.id.min)
    TextView minTv;
    @BindView(R.id.sec)
    TextView sceTv;

    @BindView(R.id.recording_iv)
    ImageView recordingImg;


    @BindView(R.id.stopwatch_linear)
    LinearLayout stopwatchLinear;
    private MediaRecorder recorder;

    private int BASE = 600;
    private int SPACE = 200;// 间隔取样时间
    private boolean isPaused = false;
    private String timeUsed;
    private int timeUsedInsec;
    private int timeUsedInsecCountdown = 5;
    private Handler uiHandle = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    if (!isPaused) {
                        addTimeUsed();
                        updateClockUI();

                    }
                    uiHandle.sendEmptyMessageDelayed(1, 1000);
                    break;
                case 2:
                    if (!isPaused) {
                        subtractTimeUsed();
                        if (timeUsed.equals("-1")) {
                            uiHandle.removeMessages(1);
                            uiHandle.removeMessages(2);

                            startTime();
                        } else if (timeUsed.equals("-2")) {

                            stopwatchLinear.setVisibility(View.VISIBLE);
                            countdownTv.setVisibility(View.GONE);
                            backImg.setImageResource(R.mipmap.cantant_red);
                        } else {
                            countdownTv.setText(timeUsed);
                        }

                    }
                    uiHandle.sendEmptyMessageDelayed(2, 1000);
                    break;

                case 3:

                default:
                    break;
            }
        }


    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cantata);
        ButterKnife.bind(this);

        /**
         * 秒表
         */
        uiHandle.removeMessages(1);
        uiHandle.removeMessages(2);
        startCountdownTime();
        isPaused = false;
        stopwatchLinear.setVisibility(View.GONE);
        countdownTv.setVisibility(View.VISIBLE);
        imageAnim();
    }


    public void imageAnim() {
        AlphaAnimation alphaAnimation1 = new AlphaAnimation(0.1f, 1.0f);
        alphaAnimation1.setDuration(800);
        alphaAnimation1.setRepeatCount(Animation.INFINITE);
        alphaAnimation1.setRepeatMode(Animation.REVERSE);
        recordingImg.setAnimation(alphaAnimation1);
        alphaAnimation1.start();
    }


    private void startTime() {
        uiHandle.sendEmptyMessageDelayed(1, 1000);
    }

    private void startCountdownTime() {
        uiHandle.sendEmptyMessageDelayed(2, 1000);
    }


    /**
     * 更新时间的显示
     */
    private void updateClockUI() {
        minTv.setText(getMin() + " : ");
        sceTv.setText(getSec());
    }

    public void addTimeUsed() {
        timeUsedInsec = timeUsedInsec + 1;
        timeUsed = this.getMin() + " : " + this.getSec();
    }

    public void subtractTimeUsed() {
        --timeUsedInsecCountdown;
        timeUsed = this.getCountdownSec() + "";
    }


    public CharSequence getMin() {

        if (timeUsedInsec / 60 < 10) {
            return String.valueOf("0" + timeUsedInsec / 60);
        } else {
            return String.valueOf(timeUsedInsec / 60);
        }
    }

    public CharSequence getSec() {
        int sec = timeUsedInsec % 60;
        return sec < 10 ? "0" + sec : String.valueOf(sec);
    }

    public CharSequence getCountdownSec() {
        int sec = timeUsedInsecCountdown % 60;

        return sec < 10 ? "" + sec : String.valueOf(sec);
    }


    private void initializeAudio() {

        Log.e("juanzhijia", "==================录制中");
        recorder = new MediaRecorder();// new出MediaRecorder对象
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        // 设置MediaRecorder的音频源为麦克风
        recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
        // 设置MediaRecorder录制的音频格式
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        // 设置MediaRecorder录制音频的编码为amr.
        recorder.setOutputFile("/sdcard/kege.amr");
        // 设置录制好的音频文件保存路径
        try {
            recorder.prepare();// 准备录制
            Log.e("juanzhijia", "====开始==============录制中");
            recorder.start();// 开始录制

        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //根据麦克风获得录音分贝
    private void updateMicStatus() {
        if (recorder != null && backImg != null) {
            // int vuSize = 10 * mMediaRecorder.getMaxAmplitude() / 32768;
            int ratio = recorder.getMaxAmplitude() / BASE;
            int db = 0;// 分贝
            if (ratio > 1)
                db = (int) (20 * Math.log10(ratio));
            System.out.println("分贝值：" + db + "     " + Math.log10(ratio));
            switch (db / 4) {
                case 0:
                    back1Img.setImageResource(R.mipmap.cantant_back_1);
                    back2Img.setImageResource(R.mipmap.cantant_back_2);
                    back3Img.setImageResource(R.mipmap.cantant_back_3);
                    break;
                case 1:
                    back1Img.setImageResource(R.mipmap.cantant_red_1);
                    back2Img.setImageResource(R.mipmap.cantant_back_2);
                    back3Img.setImageResource(R.mipmap.cantant_back_3);
                    break;
                case 2:
                    back1Img.setImageResource(R.mipmap.cantant_red_1);
                    back2Img.setImageResource(R.mipmap.cantant_red_2);
                    back3Img.setImageResource(R.mipmap.cantant_back_3);
                    break;
                case 3:
                    back1Img.setImageResource(R.mipmap.cantant_red_1);
                    back2Img.setImageResource(R.mipmap.cantant_red_2);
                    back3Img.setImageResource(R.mipmap.cantant_red_3);
                    break;


                default:
                    break;
            }
        }
    }


    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        isPaused = true;
    }


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        isPaused = false;

    }

}
